import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

///
/// 手机号输入框
///
class QPhoneTextField extends StatefulWidget {
  final TextEditingController phoneController;
  final String holdText;
  final Function? callBack;
  final bool showClear; // 是否显示清除按钮
  final TextAlign? textAlign;

  const QPhoneTextField({
    Key? key,
    required this.phoneController,
    required this.holdText,
    this.textAlign,
    this.showClear = true,
    this.callBack,
  }) : super(key: key);

  @override
  _QPhoneTextFieldState createState() => _QPhoneTextFieldState();
}

class _QPhoneTextFieldState extends State<QPhoneTextField> {
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: TextField(
            controller: widget.phoneController,
            style: const TextStyle(fontSize: 17, color: Colors.black),
            textAlign: widget.textAlign ?? TextAlign.left,
            keyboardType: TextInputType.phone,
            decoration: InputDecoration(
              isCollapsed: true, // 高度包裹
              border: InputBorder.none,
              hintText: widget.holdText,
              hintStyle: const TextStyle(
                fontSize: 17,
                color: Color.fromRGBO(153, 153, 153, 1),
              ),
            ),
            inputFormatters: [
              LengthLimitingTextInputFormatter(11),
              FilteringTextInputFormatter.allow(RegExp("[0-9]"))
            ],
            onChanged: (value) {
              setState(() {});
              if (widget.callBack != null) {
                widget.callBack!(value);
              }
            },
          ),
        ),
        widget.showClear
            ? Offstage(
                offstage: widget.phoneController.text != '' ? false : true,
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      widget.phoneController.text = '';
                    });
                    if (widget.callBack != null) {
                      widget.callBack!("");
                    }
                  },
                  child: Container(
                    height: 13,
                    width: 13,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30),
                      color: const Color.fromRGBO(161, 165, 169, 1),
                    ),
                    child: const Icon(
                      Icons.close_rounded,
                      size: 10,
                      color: Colors.white,
                    ),
                  ),
                ),
              )
            : Container(),
      ],
    );
  }
}
